package com.zhkj.txg.module.home.vm

import android.app.Application
import androidx.lifecycle.MutableLiveData
import com.zhkj.lib.base.BaseViewModel
import com.zhkj.lib.http.HttpResponse
import com.zhkj.lib.http.SubscribeListener
import com.zhkj.lib.http.ViewModelSubscribeListener
import com.zhkj.lib.utils.AccountManager
import com.zhkj.txg.base.CustomApplication
import com.zhkj.txg.base.DaoMaster
import com.zhkj.txg.base.SearchHistory
import com.zhkj.txg.base.SearchHistoryDao
import com.zhkj.txg.module.home.entity.SearchProductResponse
import com.zhkj.txg.module.home.entity.ShareInfoResponse
import com.zhkj.txg.module.home.model.HomeManager
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers

const val DATABASE_NAME = "search_history"

class SearchViewModel(application: Application) : BaseViewModel(application) {

    private val manager = HomeManager()
    private val searchHistoryDao: SearchHistoryDao

    val historyLiveData = MutableLiveData<MutableList<SearchHistory>>()
    val productListLiveData = MutableLiveData<HttpResponse<SearchProductResponse>>()
    val shareInfoLiveData = MutableLiveData<HttpResponse<ShareInfoResponse>>()

    private val numb = 20
    var page = 1
        private set

    var shopId: Long = 0
    var catId: Long = 0
    var shopCatId: Long = 0
    var type: Int = 0

    init {
        val db = DaoMaster.DevOpenHelper(getApplication<CustomApplication>(), DATABASE_NAME).writableDb
        searchHistoryDao = DaoMaster(db).newSession().searchHistoryDao
    }

//    fun searchProduct(searchKey: String, restart: Boolean = false) {
//        val listener = object :
//            ViewModelSubscribeListener<SearchProductResponse>(productListLiveData) {
//            override fun onSuccess(resp: SearchProductResponse) {
//                resp.hasMore = resp.data.size >= numb
//                resp.loadMore = page > 1
//                super.onSuccess(resp)
//                page += 1
//            }
//        }
//        if (restart) {
//            page = 1
//            saveSearchKey(searchKey)
//        }
//        val searchProduct = manager.searchProduct(
//            AccountManager.getToken(), shopId.toInt(), catId.toInt(), shopCatId.toInt(), "weigh",
//            "asc", type, searchKey, page, numb, listener
//        )
//        dispose.add(searchProduct)
//    }

    fun searchProduct(search: String, restart: Boolean = false) {
        val listener = object :
            ViewModelSubscribeListener<SearchProductResponse>(productListLiveData) {
            override fun onSuccess(resp: SearchProductResponse) {
                resp.hasMore = resp.data.size >= numb
                resp.loadMore = page > 1
                super.onSuccess(resp)
                page += 1
            }
        }
        if (restart) page = 1
        val searchProduct = manager.searchProduct(
            token = AccountManager.getToken(),
            shopId = shopId.toInt(),
            activeType = 0,
            search = search,
            catId = catId.toInt(),
            sort = "weigh",
            sortAsc = "asc",
            page = page.toString(),
            rows = numb.toString(),
            recommend = null,
            listener = listener
        )
        dispose.add(searchProduct)
    }


    fun shareInfo(id: Long) {
        val listener = ViewModelSubscribeListener(shareInfoLiveData)
        val shareInfo = manager.shareInfo(AccountManager.getToken(), id, listener)
        dispose.add(shareInfo)
    }

    /**
     * 根据用户ID搜索历史记录
     */
    fun getSearchKey() {
        val userId = AccountManager.getUserId()
        val subscribe = Observable.create<MutableList<SearchHistory>> {
            val list = searchHistoryDao.queryBuilder()
                .where(SearchHistoryDao.Properties.UserId.eq(userId))
                .orderDesc(SearchHistoryDao.Properties.CreateTime).list()
            it.onNext(list)
            it.onComplete()
        }.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe({
            historyLiveData.value = it
        }, { it.printStackTrace() })
        dispose.add(subscribe)
    }

    /**
     * 保存搜索历史
     * @param searchKey 关键字
     */
    private fun saveSearchKey(searchKey: String) {
        val userId = AccountManager.getUserId()
        val subscribe = Observable.create<SearchHistory> {
            // 获取所有的搜索记录
            val list = searchHistoryDao.queryBuilder()
                .where(
                    SearchHistoryDao.Properties.UserId.eq(userId),
                    SearchHistoryDao.Properties.SearchKey.eq(searchKey)
                )
                .orderDesc(SearchHistoryDao.Properties.CreateTime).list()
            // 判断是否搜索过改关键字
            val searchItem =
                if (list.isEmpty()) SearchHistory(null, userId, searchKey, System.currentTimeMillis()).apply {
                    update = false
                }
                else list[0].apply {
                    createTime = System.currentTimeMillis()
                }
            it.onNext(searchItem)
            it.onComplete()
        }.subscribeOn(Schedulers.io()).subscribe({
            if (it.update) searchHistoryDao.update(it)
            else searchHistoryDao.insert(it)
        }, { it.printStackTrace() })
        dispose.add(subscribe)
    }

    /**
     * 清除用户的搜索历史
     */
    fun cleanSearchKey() {
        val userId = AccountManager.getUserId()
        val subscribe = Observable.create<MutableList<SearchHistory>> {
            // 获取对应用户所有的搜索记录
            val list = searchHistoryDao.queryBuilder()
                .where(SearchHistoryDao.Properties.UserId.eq(userId))
                .orderDesc(SearchHistoryDao.Properties.CreateTime).list()
            it.onNext(list)
            it.onComplete()
        }.subscribeOn(Schedulers.io()).subscribe({
            if (it.isNotEmpty()) searchHistoryDao.deleteInTx(it)
            // 发送空历史记录
            historyLiveData.postValue(mutableListOf())
        }, { it.printStackTrace() })
        dispose.add(subscribe)
    }
}